<template>
  <div class="cesium-dropdown">
    <div class="dropdown-trigger" @click="toggleDropdown">
      <span>{{ modelValue ? optionsMap[modelValue] : placeholder }}</span>
      <i class="arrow-down"></i>
    </div>
    <transition name="dropdown">
      <div v-show="isOpen" class="dropdown-menu">
        <div
          v-for="(label, value) in optionsMap"
          :key="value"
          class="dropdown-item"
          :class="{ active: modelValue === value }"
          @click="selectOption(value)"
        >
          {{ label }}
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  optionsMap: {
    type: Object,
    required: true
  },
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const isOpen = ref(false)

const toggleDropdown = () => {
  isOpen.value = !isOpen.value
}

const selectOption = (value) => {
  emit('update:modelValue', value)
  emit('change', value)
  isOpen.value = false
}

// 点击外部关闭下拉框
const closeOnClickOutside = (e) => {
  if (!e.target.closest('.cesium-dropdown')) {
    isOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', closeOnClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeOnClickOutside)
})
</script>

<style scoped lang="scss">
.cesium-dropdown {
  position: relative;
  
  .dropdown-trigger {
    background: #303336;
    border: 1px solid #444;
    color: #edffff;
    padding: 3px 8px;
    border-radius: 4px;
    cursor: pointer;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-width: 90px;
    user-select: none;
    font-size: 12px;

    &:hover {
      background: #48b;
      border-color: #aef;
      box-shadow: 0 0 8px #fff;
    }

    .arrow-down {
      border-top: 4px solid #edffff;
      border-left: 4px solid transparent;
      border-right: 4px solid transparent;
      margin-left: 8px;
    }
  }

  .dropdown-menu {
    position: absolute;
    top: 100%;
    left: 0;
    margin-top: 4px;
    background: #303336;
    border: 1px solid #444;
    border-radius: 4px;
    width: 100%;
    z-index: 100;
  }

  .dropdown-item {
    padding: 8px 8px;
    color: #edffff;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 12px;

    &:hover {
      background: #48b;
    }

    &.active {
      background: #1a1a1a;
    }
  }
}

.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.3s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style> 